package com.wpf.system.security.handler;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.wpf.system.common.utils.JWTUtils;
import com.wpf.system.common.utils.RedisUtils;
import com.wpf.system.mapper.UserMapper;
import com.wpf.system.security.LoginResult;
import com.wpf.system.security.LoginUser;
import io.jsonwebtoken.Jwts;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Resource
    private JWTUtils jwtUtils;

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private UserMapper userMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream out = httpServletResponse.getOutputStream();

        LoginUser loginUser = (LoginUser)authentication.getPrincipal();
        String token = jwtUtils.generateToken(loginUser);
        long expireTime = Jwts.parser()
                .setSigningKey(jwtUtils.getSecret())
                .parseClaimsJws(token.replace("jwt_", ""))
                .getBody().getExpiration().getTime();

        LoginResult loginResult = new LoginResult();
        loginResult.setCode(200);
        loginResult.setId(loginUser.getUser().getId());
        loginResult.setToken(token);
        loginResult.setExpireTime(expireTime);

        //记录登录时间
        loginUser.getUser().setLoginTime(DateUtil.date());
        userMapper.updateById(loginUser.getUser());

        //把生成的token存到redis
        String tokenKey = "token_"+token;
        redisUtils.set(tokenKey,token,jwtUtils.getExpiration() / 1000);

        //清除验证码缓存
        String code = httpServletRequest.getParameter("code");
        String ip = httpServletRequest.getRemoteAddr();
        String key = ip+code;
        redisUtils.del(key);

        String res =  JSONObject.toJSONString(loginResult, SerializerFeature.DisableCircularReferenceDetect);

        out.write(res.getBytes(StandardCharsets.UTF_8));
        out.flush();
        out.close();
    }
}
